#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#  Copyright (c) Huoty - All rights reserved
#
#      Author: Huoty <sudohuoty@gmail.com>
#  CreateTime: 2016-09-30 13:45:12
# *************************************************************

"""服务器端核心结构"""

import os
import json

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from ..utils import log
from ..utils import sha1, md5, AESCipher, json_dumps
from .wechat import dami_baby_wechat as wechat
from .handlers import IndexHandler, ApiHandler, WechatHandler


class Application(tornado.web.Application):
    """应用程序"""
    def __init__(self, debug=False):
        handlers = [
            (r'/', IndexHandler),
            (r'/wx/api', WechatHandler),
            (r'/api', ApiHandler, dict(db="")),
        ]

        settings = dict(
            template_path = os.path.join(os.path.dirname(__file__), "templates"),
            static_path = os.path.join(os.path.dirname(__file__), "static"),
            debug = debug,
            autoreload = True,
        )

        tornado.web.Application.__init__(self, handlers, **settings)


def main():
    from tornado.options import define, options, parse_command_line
    define("port", default=8002, help="run on the given port", type=int)
    define("debug", default=False, help="debug mode", type=bool)
    parse_command_line()

    app = Application(options.debug)
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    log.info("* Server started at http://127.0.0.1:%s/ (Press CTRL+C to quit)" % options.port)
    tornado.ioloop.IOLoop.instance().start()


# Script starts from here

if __name__ == "__main__":
    main()
